package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsCategory;
import com.qf.service.CategoryService;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    //http://localhost:8083/admin/category/list?page=1&limit=20&sort=add_time&order=desc
    @GetMapping("/list")
    public Object list(Integer id, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "add_time") String sort,
                       @RequestParam(defaultValue = "desc") String order) {
        IPage<DtsCategory> categoryIPage = categoryService.queryByPage
                (id, name, page, limit, sort, order);
        long total = categoryIPage.getTotal();
        List<DtsCategory> records = categoryIPage.getRecords();

        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("items", records);
        return ResponseUtil.ok(map);
    }

    //##### 商品一级类目列表
    //
    //- 接口地址 : http://localhost:8083/admin/category/l1

    @RequestMapping("/l1")
    public Object list() {
        List<CatVo> dtsCategories = categoryService.list1();
        return ResponseUtil.ok(dtsCategories);
    }

//    ##### 商品类目添加
//
//- 接口地址 : http://localhost:8083/admin/category/create

    @RequestMapping("/create")
    public Object create(@RequestBody DtsCategory category) {
        DtsCategory dtsCategory = categoryService.addOne(category);
        return ResponseUtil.ok(dtsCategory);
    }

    //##### 商品类目编辑
    //
    //- 接口地址 : http://localhost:8083/admin/category/update

    @PostMapping("/update")
    public Object update(@RequestBody DtsCategory category) {
        int updateOne = categoryService.updateOne(category);
        if (updateOne == 0) {
            new RuntimeException("修改失败");
        }
        return ResponseUtil.ok(category);
    }

    //http://localhost:8083/admin/brand/delete
    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsCategory category) {
        categoryService.deleteOne(category);
        return ResponseUtil.ok();
    }


}
